package com.jet.chat.service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import com.jet.chat.exception.ChatExceptionDBService;

public class DBConnectionService {
	private String dbURL;
	private Connection conn = null;
	
	public DBConnectionService(String dbname) {
		dbURL = "jdbc:derby:" + dbname + ";create=true";
	}

	public boolean isConnected() {
		return conn != null;
	}
	
	public Connection getConn() {
		return this.conn;
	}

	public void createConnection() throws ChatExceptionDBService {
			try {
				Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
			} catch (InstantiationException e) {
				throw new ChatExceptionDBService("ошибка инициализирования пользователя базы данных");
			} catch (IllegalAccessException e) {
				throw new ChatExceptionDBService("ошибка доступа базы данных");
			} catch (ClassNotFoundException e) {
				throw new ChatExceptionDBService("драйвер базы данных не найден");
			}
			
			try {
				this.conn = DriverManager.getConnection(this.dbURL);
			} catch (SQLException e) {
				throw new ChatExceptionDBService("database getting connection error");
			}
	}
	
	public void shutdown() {
		try {
			if (this.conn != null) {
				this.conn.close();
			}           
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
}
